# /usr/bin/env python
# encoding=utf-8

from tkinter.filedialog import *
from tkinter.colorchooser import *
from tkinter.filedialog import *

class Application4NotePad(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.textpad = None
        self.pack()
        self.createWidget()


    def createWidget(self):
        menubar = Menu(root)

        #增加快捷键的处理
        root.bind("<Control-n>", lambda event:self.newFile())
        root.bind("<Control-o>", lambda event: self.openFile())
        root.bind("<Control-s>", lambda event: self.saveFile())
        root.bind("<Control-q>", lambda event: self.exit())

        menuFile = Menu(menubar)
        menuEdit = Menu(menubar)
        menuHelp = Menu(menubar)

        menubar.add_cascade(label="文件(F)", menu=menuFile)
        menubar.add_cascade(label="编辑(E)", menu=menuEdit)
        menubar.add_cascade(label="帮助(H)", menu=menuHelp)

        menuFile.add_command(label="新建", accelerator="ctrl+n", command=self.newFile)
        menuFile.add_command(label="打开", accelerator="ctrl+o", command=self.openFile)
        menuFile.add_command(label="保存", accelerator="ctrl+s", command=self.saveFile)
        menuFile.add_separator()  # 添加文本分割线
        menuFile.add_command(label="退出", accelerator="ctrl+q", command=self.exit)

        # 将主菜单加到根窗口
        root["menu"] = menubar

        # 文本编辑区
        self.textpad = Text(root, width=50, height=30)
        self.textpad.pack()

        # 创建上下菜单
        self.contextMenu = Menu(root)
        self.contextMenu.add_command(label="背景颜色", command=self.openAakColor)

        # 为右键绑定事件
        root.bind("<Button-3>", self.createContextMenu)

    def openAakColor(self):
        s1 = askcolor(color="red", title="选择背景色")
        self.textpad.config(bg=s1[1])


    def newFile(self):
        self.filename = asksaveasfilename(title="另存为", initialfile="未命名.txt",
                          filetypes=[('文本文档',"*.txt")],
                          defaultextension=".txt")
        self.saveFile()

    def openFile(self):
        self.textpad.delete("1.0", "end")  #吧text控件中所有的内容清空
        with askopenfile(title="打开文本文件") as f:
            print(f.read())
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name

    def saveFile(self):
        with open(self.filename, "w") as f:
            c = self.textpad.get(1.0, END)
            f.write(c)

    def exit(self):
        root.quit()

    def createContextMenu(self, event):
        self.contextMenu.post(event.x_root, event.y_root)


if __name__ == "__main__":
    root = Tk()
    root.geometry("450x300+200+100")
    root.title("百战程序员的简易记事本")
    app = Application4NotePad(master=root)
    root.mainloop()

